#!/bin/bash

set -e

# Remove quotes and commas
EXPORTED_FUNCTIONS=$(                     \
    cat lib/src/wasm/stdlib-symbols.txt | \
    tr -d ',"'                            \
)

EXPORT_FLAGS=""
for function in ${EXPORTED_FUNCTIONS}; do
    EXPORT_FLAGS+=" -Wl,--export=${function}"
done

target/wasi-sdk-21.0/bin/clang-17   \
    -o stdlib.wasm                  \
    -Os                             \
    -fPIC                           \
    -Wl,--no-entry                  \
    -Wl,--stack-first               \
    -Wl,-z -Wl,stack-size=65536     \
    -Wl,--import-undefined          \
    -Wl,--import-memory             \
    -Wl,--import-table              \
    -Wl,--strip-debug               \
    -Wl,--export=reset_heap         \
    -Wl,--export=__wasm_call_ctors  \
    -Wl,--export=__stack_pointer    \
    ${EXPORT_FLAGS}                 \
    lib/src/wasm/stdlib.c

xxd -C -i stdlib.wasm > lib/src/wasm/wasm-stdlib.h
mv stdlib.wasm target/
